package com.example.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 登录检查过滤器 - 判断用户登录状态，未登录时强制跳转到登录页面
 */
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    // 不需要登录就可以访问的资源列表
    private static final List<String> EXCLUDE_URLS = Arrays.asList(
            "/login.jsp",
            "/login",
            "/logout",
            "/verifyCode",
            "/css/",
            "/js/",
            "/images/"
    );

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginCheckFilter initialized");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取请求URI
        String uri = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        String path = uri.substring(contextPath.length());

        // 检查是否是不需要登录的资源
        if (isExcluded(path)) {
            chain.doFilter(request, response);
            return;
        }

        // 获取session
        HttpSession session = httpRequest.getSession(false);

        // 检查用户是否已登录
        if (session == null || session.getAttribute("currentUser") == null) {
            // 未登录，跳转到登录页面
            httpResponse.sendRedirect(contextPath + "/login.jsp");
            return;
        }

        // 已登录，继续访问
        chain.doFilter(request, response);
    }

    /**
     * 判断请求路径是否在排除列表中
     */
    private boolean isExcluded(String path) {
        // 根路径放行
        if (path.equals("/") || path.isEmpty()) {
            return true;
        }

        // 检查是否在排除列表中
        for (String excludeUrl : EXCLUDE_URLS) {
            if (path.equals(excludeUrl) || path.startsWith(excludeUrl)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void destroy() {
        System.out.println("LoginCheckFilter destroyed");
    }
}

